package user

import (
	"context"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
	"time"
	"yangming-college/app/usercenter/cmd/v1/api/internal/svc"
	"yangming-college/app/usercenter/cmd/v1/api/internal/types"
	"yangming-college/common/cryptx"
	"yangming-college/common/jwtx"
	. "yangming-college/common/snowflake"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterResp, err error) {
	// 判断手机号是否已经注册
	var account types.Account
	err = l.svcCtx.DB.Where("phone = ?", req.Phone).First(&account).Error
	if err != nil {
		//没有注册
		accountId := GenSnowflakeID() //生成账号雪花ID
		if accountId == 0 {
			return nil, errors.Wrapf(err, "生产账号ID失败")
		}

		if err == gorm.ErrRecordNotFound {
			//todo redis手机验证码
			if req.Code != 123456 {
				return nil, errors.Wrapf(err, "手机验证码出错")
			}

			newAccount := types.Account{
				Email:         req.Email,
				Phone:         req.Phone,
				Password:      cryptx.PasswordEncrypt(l.svcCtx.Config.Salt, req.Password),
				Nickname:      "学者",
				AccountId:     accountId,
				CreatedAt:     time.Now().Unix(),
				UpdatedAt:     time.Now().Unix(),
				NameMtime:     time.Now().Unix(),
				LastLoginTime: time.Now().Unix(),
				RoleId:        1,
			}

			if err := l.svcCtx.DB.Create(&newAccount).Error; err != nil {
				return nil, errors.Wrapf(err, "创建用户失败")
			}

			//生成token
			now := time.Now().Unix()
			accessExpire := l.svcCtx.Config.JwtAuth.AccessExpire
			accessToken, err := jwtx.GetToken(l.svcCtx.Config.JwtAuth.AccessSecret, now, accessExpire, accountId)
			if err != nil {
				return nil, errors.Wrapf(err, "生成token失败")
			}

			return &types.RegisterResp{
				AccessToken:  accessToken,
				AccessExpire: now + accessExpire,
				RefreshAfter: now + accessExpire/2,
			}, nil
		} else {
			return nil, errors.Wrapf(err, "查找手机号出错")
		}
	}

	return nil, errors.Wrapf(err, "注册失败")
}
